from concurrent.futures import ThreadPoolExecutor
from typing import Callable

from emi.core.MainEventEngine import MainEventEngine


class AsyUtil:
    __engine:MainEventEngine = MainEventEngine()
    __thread_pool = ThreadPoolExecutor(max_workers=20)

    @staticmethod
    def run_io_thread(function: Callable, args: dict = {}, delay_second=0):
        """
        在UI线程处理。
        """
        AsyUtil.__check_engine_run()
        AsyUtil.__engine.postDelay(delay_second, function, args,None)

    @staticmethod
    def run_in_thread( *args, **kwargs):
        """
        提交任务在后台线程执行。不可以控制的后台任务。
        :param fun:
        :return:
        """
        thread_obj = AsyUtil.__thread_pool.submit(*args,**kwargs)
        thread_obj.add_done_callback(AsyUtil._on_run_in_thread_call_back)

    @staticmethod
    def _on_run_in_thread_call_back(worker):
        worker_exception = worker.exception()
        if worker_exception:
            raise worker_exception


    @staticmethod
    def __check_engine_run():
        if not AsyUtil.__engine.is_running():
            AsyUtil.__engine.run()